package logic

import (
	"context"
	"errors"
	"math/rand"
	"strconv"
	"time"
	"user-login/moder/cache"
	"user-login/pkg"

	"user-login/userrpc/internal/svc"
	"user-login/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *userrpc.SendSmsRequest) (*userrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line

	i, _ := cache.Rdb.Get(l.ctx, "sendsmsbind"+in.Username).Int()

	if i >= 1 {
		return nil, errors.New("一分钟只能发送一次")
	}

	code := rand.Intn(9000) + 1000
	sms, err := pkg.SendSms(in.Username, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if sms.Code != 2 {
		return nil, errors.New(sms.Msg)
	}

	i1, _ := cache.Rdb.Incr(l.ctx, "sendsmsbind"+in.Username).Result()

	if i1 >= 1 {
		cache.Rdb.Expire(l.ctx, "sendsmsbind"+in.Username, time.Minute*1)
	}
	return &userrpc.SendSmsResponse{}, nil
}
